package com.bw.home.view

import android.util.Log
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.bw.base.app.RoutePath
import com.bw.common.entity.SimpleVideoEntity
import com.bw.common.mvi.BaseMviFragment
import com.bw.home.R
import com.bw.home.adapter.HomePlayAdapter
import com.bw.home.databinding.FragmentHomeBinding
import com.bw.home.entity.SimpleTypeEntity
import com.bw.home.intent.HomeViewIntent
import com.bw.home.state.HomeUiState
import com.bw.home.vm.HomeViewModel
import com.luck.picture.lib.utils.ToastUtils
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMVideo


import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
@Route(path = RoutePath.PATH_FRAGMENT_HOME)
class HomeFragment : BaseMviFragment<FragmentHomeBinding>() {

//    private val mViewModel: HomeViewModel by activityViewModels()
//    private val mTabList = mutableListOf<SimpleTypeEntity>()
//    private val mListFragment = mutableListOf<HomeListFragment>()
//    private lateinit var homePageAdapter: HomePageAdapter


    private val homePlayViewModel: HomeViewModel by activityViewModels()
    private lateinit var homePlayAdapter: HomePlayAdapter
    private val videoList = mutableListOf<SimpleVideoEntity>()
    override fun getLayoutId(): Int = R.layout.fragment_home

    override fun initViews() {
        homePlayAdapter = HomePlayAdapter(videoList)
        mDataBinding.rv.adapter = homePlayAdapter
        mDataBinding.rv.layoutManager = LinearLayoutManager(requireContext())
        //仿抖音页面
        val helper = PagerSnapHelper()
        helper.attachToRecyclerView(mDataBinding.rv)

        mDataBinding.rv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    val layoutManager = recyclerView.layoutManager as LinearLayoutManager
                    val snapView = helper.findSnapView(layoutManager)
                    val position = snapView?.let { layoutManager.getPosition(it) } ?: return
                    val viewHolder =
                        recyclerView.findViewHolderForAdapterPosition(position) as? HomePlayAdapter.ItemViewHolder
                    viewHolder?.dataBinding?.gsy?.startPlayLogic()
                }

            }
        })

    }

    /**
     * 发起意图
     */
    // 在 sendViewIntent() 中添加日志
    override suspend fun sendViewIntent() {
        Log.d("HomeFragment", "发送请求")
        homePlayViewModel.channel.send(HomeViewIntent.LoadRecommendSimpleVideoList(2, 10))
        Log.d("HomeFragment", "发送成功")
    }


    override fun onStart() {
        super.onStart()
        // 启动协程收集UI状态
        viewLifecycleOwner.lifecycleScope.launch {
            collectUIState()
        }
        // 发送意图
        viewLifecycleOwner.lifecycleScope.launch {
            sendViewIntent()
        }
    }

    /**
     * 收集UI状态
     */
    override suspend fun collectUIState() {
        homePlayViewModel.uiSharedFlow.collect {
            when (it) {
                is HomeUiState.LoadSimpleVideoSuccess -> getVideo(it.list)
                is HomeUiState.LoadSimpleVideoFail -> Log.d("HomeFragment", "请求失败")
                else -> {}
            }
        }
    }

    private fun getVideo(list: List<SimpleVideoEntity>) {
        homePlayAdapter.setOnItemClickListener(object : HomePlayAdapter.OnItemClickListener {
            override fun onItemClick(v: View, position: Int) {
                when (v.id) {
                    R.id.iv_share -> {
                        val video: UMVideo = UMVideo(videoList[position].videopath)
                        video.setTitle(videoList[position].title) //视频的标题
                        val image = UMImage(requireActivity(), videoList[position].videopath)
                        video.setThumb(image) //视频缩略图
                        video.setDescription(videoList[position].description) //视频的描述
                        ShareAction(requireActivity())
                            .withText("hello")
                            .withMedia(video)
                            .setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QZONE)
                            .setCallback(object : UMShareListener {
                                override fun onStart(p0: SHARE_MEDIA?) {
                                }

                                override fun onResult(p0: SHARE_MEDIA?) {
                                }

                                override fun onError(p0: SHARE_MEDIA?, p1: Throwable?) {
                                    //分享失败回调
                                    ToastUtils.showToast(requireContext(), p1?.message)
                                }

                                override fun onCancel(p0: SHARE_MEDIA?) {
                                    ToastUtils.showToast(requireContext(),  "取消分享")
                                }
                            })
                            .open()
                    }
                }
            }
        })
        videoList.clear()
        videoList.addAll(list)
        homePlayAdapter.notifyDataSetChanged()
    }


}


